<?php
/**
 * epub蜘蛛
 * netxlong
 * 
 */
//var_dump($_SERVER);
//$url = 'http://localhost/stanza/zhizhu/test.php';

define('ROOT', dirname(dirname(__FILE__)));
require_once(ROOT.'/class/database.class.php');
date_default_timezone_set('PRC');
set_time_limit(0);
$base_url = 'http://218.85.74.53';
$url = "http://218.85.74.53/BookList.asp?op=catalog&Catalog=WangLuoXiaoShuo&page=7"; //地址
//$url = 'http://cnstanza.com/index.php?cateid=1'; //地址

$cookie = "Cookie: wR5_auth=b0b2OytsnyPXlUJmmF2ooKrytH9pjflmPx3pr8PbIWKtpAxN4%2Ff%2FRykDWx64dwrv%2FqoJhb4J7e7QkIoiTrEAdB14; uid=617; password=7895123; username=netxlong; ASPSESSIONIDQSCABDDQ=MEHIEPKCMBPKKFLKBGFLLCIM
Authorization: Basic bmV0eGxvbmc6Nzg5NTEyMw==
";

$age = 'Stanza/1.7 iPhone OS/2.2.1/iPod touch catalog/1.7';
$cate_id = '12';

$dblink = new DataBase();

//正则部分
$preg_books = "/<entry>(.*?)\.(.*?)<\/entry>/is";
$preg_title = "/<title>\d+\.(.*?)<\/title>/is";
$preg_author = "/<name>(.*?) 推荐度/is";
$preg_desp = "/<!\[CDATA\[(.*?)\]\]>/is";
$preg_epub = "/<link type=\"application\/epub\+zip\" href=\"(.*?)\"/is";
$preg_true_epub = "/<a href=\"(.*?)\"/is";
$preg_pic = "/<link rel=\"x-stanza-cover-image\" type=\"image\/png\" href=\"(.*?)\"\/>/is";
$preg_price = "/<span style=.*\'>(.*?)<\/span>/is";

//正则部分

$dir_name = date('Ymd');
if(!file_exists('../books/'.$dir_name)) {
    mkdir('../books/'.$dir_name);
}
if(!file_exists('../images/src/'.$dir_name)) {
    mkdir('../images/src/'.$dir_name);
}
if(!file_exists('../images/small/'.$dir_name)) {
    mkdir('../images/small/'.$dir_name);
}
if(!file_exists('../images/big/'.$dir_name)) {
    mkdir('../images/big/'.$dir_name);
}

require_once("HTTP/Request.php");
$req = new HTTP_Request($url);
$req->setMethod(HTTP_REQUEST_METHOD_GET);
$req->addHeader("USER-AGENT", $age);
$req->addHeader("Connection", 'keep-alive');
if (!PEAR::isError($req->sendRequest())) {
		 $response = $req->getResponseBody();
} else {
		 $response = '';
		 die('fail fetch list');
}

//var_dump($response);
echo 'start:';
preg_match_all($preg_books, $response, $books);
$books = $books[0];
foreach ($books as $book) {
    //var_dump($book);
    echo '读取book完毕,';
        
    $name = md5(time());
    
    preg_match($preg_title, $book, $title);
    $title = $title[1]; //标题
    $title_md5 = md5($title);
    $query = "select * from books where title_md5 = '$title_md5'";
    $is_in = $dblink->query($query)->fetchColumn();
    if($is_in) {
        echo "\n书籍已存在,跳过....\n";
	    continue;
    }
    
    preg_match($preg_price, $book, $price);
    $price = $price[1];
    //var_dump($price);
    if(strlen($price) != 10) {
        echo $price."收费,跳过\n";
        continue;
    }
    
    preg_match($preg_author, $book, $author);
    $author = $author[1]; //作者
    
    preg_match($preg_desp, $book, $desp);
    $desp = $desp[1];

    /**
     * 图片部分
     */
    preg_match($preg_pic, $book, $pic_url);
    $pic_url = $base_url.$pic_url[1];
    $pic = file_get_contents($pic_url);
    $pi = 1;
    while (!$pic) {
        $pic = file_get_contents($pic_url);
        echo "\n图片获取失败,重试中....\n";
	$pi++;
	if($pi > 5) {
	    echo "\n图片获取失败,跳过....\n";
	    continue 2;
	}
    }
    
    $src_pic = ROOT."/images/src/".$dir_name.'/'.$name.".jpg";
    file_put_contents($src_pic, $pic);     
    echo '保存图片完毕,';
    //处理缩略图
    
    $big_patch = ROOT.'/images/big/'.$dir_name.'/'.$name.'.jpg';
    $small_patch = ROOT.'/images/small/'.$dir_name.'/'.$name.'.jpg';
    
    require_once(ROOT.'/class/simpleimage.class.php');
    $simple_image = new SimpleImage();
    
    $simple_image->load($src_pic);
    $simple_image->resizeToWidth(160);
    $simple_image->save($big_patch);
    
    $simple_image->load($src_pic);
    $simple_image->resizeToWidth(54);
    $simple_image->save($small_patch);
    echo '缩略图完毕,';
     
    require_once(ROOT.'/class/common.class.php');
    Common::imageWaterMark($big_patch, 8, ROOT.'/theme/watermark.png');
    echo '水印完毕.  '; 
    
    
    
    
    /**
     * epub部分
     */
    
    preg_match($preg_epub, $book, $epub_url);
    $epub_url = $base_url.'/'.$epub_url[1];
    $epub_url = str_replace('&amp;', '&', $epub_url);
    
    //开始获取epub文件URL
    $req = new HTTP_Request($epub_url);
    $req->setMethod(HTTP_REQUEST_METHOD_GET);
    $req->addHeader("USER-AGENT", $age);
    $req->addHeader("Cookie", $cookie);
    $req->addHeader("Connection", 'keep-alive');
    if (!PEAR::isError($req->sendRequest())) {
    	 $epub_response = $req->getResponseBody();
    } else {
 	 $epub_response = '';
    }
    var_dump($epub_response);
    $i = 0;
    while(!$epub_response) {
	 $epub_response = $req->getResponseBody();
	 echo "\n获取epub文件失败,重试中....\n";
	 $i++;
	 if($i > 5) {
		echo "\n获取epub文件失败,跳过\n";
		continue 2;
	 }
    }
    preg_match($preg_true_epub, $epub_response, $epub_true_url);
    $epub_true_url = $base_url.$epub_true_url[1];
    //结束获取epub文件URL
    echo '读取epub url 完毕,'.$epub_true_url;
    //var_dump($epub_true_url);
    //开始获取epub文件
    $req = new HTTP_Request($epub_true_url);
    $req->setMethod(HTTP_REQUEST_METHOD_GET);
    $req->addHeader("USER-AGENT", $age);
    $req->addHeader("Cookie", $cookie);
    $req->addHeader("Connection", 'keep-alive');
    //$req->addHeader("Authorization", "Basic bmV0eGxvbmc6Nzg5NTEyMw==");
    //var_dump($req);
    if (!PEAR::isError($req->sendRequest())) {
    		 $response = $req->getResponseBody();
    } else {
    		 $response = '';
    		 die('fail fetch list');
    }
    //var_dump($response);
    $epub_file = ROOT."/books/{$dir_name}/{$name}.epub";
    file_put_contents($epub_file, $response);
    //结束获取epub文件
    echo '保存epub完毕,'; 
    
    $epub_file_name = $name.'.epub';
    $pic_file_name = $name.'.jpg';
    $size = number_format(filesize($epub_file) / 1024, 1);
    $title_md5 = md5($title);
    $author_md5 = md5($author);
    $created_at = date('Y-m-d H:i:s');
    
    $query = "insert into books set cateid = '$cate_id', title = '$title', author = '$author', content = '$desp', file = '$epub_file_name', pic = '$pic_file_name', size = '$size', title_md5 = '$title_md5', author_md5 = '$author_md5' , created_at = '$created_at'";
    // echo $query;
    $dblink->query($query);
    
    $query = "select * from cate where id = '$cate_id'";
    $cate_info = $dblink->query($query)->fetch();
    $query = "update cate set count = '" . strval($cate_info['count'] + 1) . "' where id = '$cate_id'";
    $dblink->query($query);
    
    echo $title.'大小:'.$size."ok\n";
}
?>
